package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.entity.MessageConstant;
import com.itheima.entity.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {


    //自动装配
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/getValidateCode")
    public Result getValidateCode(String telephone){
        try {
        //获得验证码
            Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
            //发送短信
        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());

        //把验证码rides的缓存中=>用于后期验证验证码是否输入成功
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,300,validateCode.toString());

        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }


    @RequestMapping("/loginValidateCode")
    public Result loginValidateCode(String telephone){

        //获取验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        //发送
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());

            //放入rides中
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone+RedisMessageConstant.SENDTYPE_LOGIN,300,validateCode.toString());
            resource.close();
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }


    }
}
